﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DatabaseComponent;
 


public partial class UpdateEmployeeStatusEN : System.Web.UI.Page
{


    public List<Persons> mlstPersons
    {
        get
        {
            if (ViewState["mlstPersons"] == null)
                ViewState["mlstPersons"] = System.Guid.NewGuid().ToString();

            if (Session[ViewState["mlstPersons"].ToString()] == null)
                Session[ViewState["mlstPersons"].ToString()] = new List<Persons> ();

            return Session[ViewState["mlstPersons"].ToString()] as List<Persons>;
        }
        set
        {
            if (ViewState["mlstPersons"] == null)
                ViewState["mlstPersons"] = System.Guid.NewGuid().ToString();
            Session[ViewState["mlstPersons"].ToString()] = value;
        }
    }


    public List<RegisteredCourses> mlstRegestered
    {
        get
        {
            if (ViewState["mlstRegestered"] == null)
                ViewState["mlstRegestered"] = System.Guid.NewGuid().ToString();

            if (Session[ViewState["mlstRegestered"].ToString()] == null)
                Session[ViewState["mlstRegestered"].ToString()] = new List<RegisteredCourses>();

            return Session[ViewState["mlstRegestered"].ToString()] as List<RegisteredCourses>;
        }
        set
        {
            if (ViewState["mlstRegestered"] == null)
                ViewState["mlstRegestered"] = System.Guid.NewGuid().ToString();

            Session[ViewState["mlstRegestered"].ToString()] = value;
        }
    }



    public Persons mobjUser
    {
        get
        {
            if (ViewState["mobjUser"] == null)
                ViewState["mobjUser"] = System.Guid.NewGuid().ToString();

            if (Session[ViewState["mobjUser"].ToString()] == null)
                Session[ViewState["mobjUser"].ToString()] = new Persons();

            return Session[ViewState["mobjUser"].ToString()] as Persons;
        }
        set
        {
            if (ViewState["mobjUser"] == null)
                ViewState["mobjUser"] = System.Guid.NewGuid().ToString();

            Session[ViewState["mobjUser"].ToString()] = value;
        }
        
    }




    protected void Page_Load(object sender, EventArgs e)
    {

        if (!Page.IsPostBack)
        {
            mobjUser = GlobalVars.getCurrentPerson();
            checkSecurityAndCustomizePage(mobjUser);
            bindGrid("");
            
        }




    }


    /// <summary>
    /// this function will bind the persons grid due to a search text
    /// </summary>
    /// <param name="strSearch">the text to search for</param>
    private void bindGrid(string strSearch)
    {

        mlstPersons = search(strSearch);

        grdUsers.DataSource = mlstPersons;
        grdUsers.DataBind();
    }


   


    /// <summary>
    /// this function will check the security and if not found it will redirect
    /// </summary>
    /// <param name="mobjUser">the user to check its priveleges</param>
    private void checkSecurityAndCustomizePage(Persons mobjUser)
    {
        if (!mobjUser.lstAllRulesIDs.Contains((long)RulesEnum.Change_User_Status_Page))
        {
            Response.Redirect("LoginEN.aspx");
        }
    }




    /// <summary>
    /// this function will search in Persons and return the values
    /// </summary>
    /// <param name="txtText">the text to search for</param>
    /// <returns>a list of Persons  matched</returns>
    public static List<Persons> search(string txtText)
    {

        PersonsDB objPersonsDB = new PersonsDB(ConnectionStrings.LMS);
        List<Persons> lstRet = new List<Persons>();

        if (txtText.Trim() == "")
        {
            List<Persons> lstNew = objPersonsDB.Select(" top 100 ", " order by [Name_EN] ");
            //lstNew = new List<Persons>(from objFol in lstNew where objFol.StatusID != 2 select objFol);
            return lstNew;
        }


        string[] strValues = null;
        if (txtText.Trim()[0] == '\"' && txtText.Trim()[txtText.Trim().Length - 1] == '\"')
        {
            try
            {
                strValues = new string[] { txtText.Trim().Substring(1, txtText.Trim().Length - 2) };
                if (strValues[0] == "")
                    strValues = new string[0];
            }
            catch
            {
                strValues = new string[0];
            }
        }
        else
        {
            strValues = txtText.Trim().Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
        }



        foreach (string strValue in strValues)
        {
            Persons objPersons = new Persons();
            objPersons.Badge = objPersons.ID = objPersons.FamilyName_AR = objPersons.FamilyName_EN = objPersons.Name_AR = objPersons.Name_EN =
                objPersons.MiddleName_AR = objPersons.MiddleName_EN = "%" + strValue + "%";

            List<Persons> lstPersons = objPersonsDB.SearchLikeOROrderByNAME_EN(objPersons);
            //lstPersons = new List<Persons>(from objFol in lstPersons where objFol.StatusID != 2 select objFol);

            foreach (Persons objFol in lstPersons)
            {
                if ((from objIn in lstRet where objIn.GenID == objFol.GenID select objIn).ToList().Count == 0)
                {
                    lstRet.Add(objFol);
                }
            }

        }


        return lstRet;



    }


    protected void grdUsers_RowEditing(object sender, GridViewEditEventArgs e)
    {
        long PersonID = long.Parse( grdUsers.DataKeys[e.NewEditIndex]["GenID"].ToString());

        bindSmallGrid(PersonID);


        e.Cancel = true ;
    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        bindGrid(txtSearch.Text);
    }
    protected void grdUsers_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grdUsers.DataSource = mlstPersons;
        grdUsers.PageIndex = e.NewPageIndex;
        grdUsers.DataBind();
    }

    protected void grdCourses_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DropDownList ddlStatus = e.Row.FindControl("ddlStatus") as DropDownList;
            
            CourseStatusDB objCourseStatusDB = new CourseStatusDB (ConnectionStrings.LMS);
            List<CourseStatus> lstCourseStatus = objCourseStatusDB.Select("", "");

            ddlStatus.DataSource = lstCourseStatus;
            ddlStatus.DataTextField = "CourseStatusEN";
            ddlStatus.DataValueField = "ID";

            ddlStatus.DataBind();





            ddlStatus.SelectedValue = ((RegisteredCourses)e.Row.DataItem).CourseStatus.ToString();
            
        }
    }
    protected void grdCourses_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grdCourses.DataSource = mlstRegestered;
        grdCourses.PageIndex = e.NewPageIndex;
        grdCourses.DataBind();
    }
    protected void grdCourses_RowEditing(object sender, GridViewEditEventArgs e)
    {

        long RegisteredID = long.Parse( grdCourses.DataKeys[e.NewEditIndex]["ID"].ToString());
        RegisteredCoursesDB objRegisteredCoursesDB = new RegisteredCoursesDB(ConnectionStrings.LMS);
        CoursesScoesDB objCourseScoesDB = new CoursesScoesDB(ConnectionStrings.LMS);
        List<RegisteredCourses> lstFound = objRegisteredCoursesDB.getRegisteredCoursesByID(RegisteredID);

        if (lstFound.Count > 0)
        {

            RegisteredCourses objRegisteredCourses = lstFound[0];

            



            DropDownList ddlStatus = grdCourses.Rows[e.NewEditIndex].FindControl("ddlStatus") as DropDownList;


            if (ddlStatus != null)
            {
                if (long.Parse(ddlStatus.SelectedValue) != objRegisteredCourses.CourseStatus)
                {
                    objRegisteredCourses.CourseStatus = long.Parse(ddlStatus.SelectedValue);
                    if (ddlStatus.SelectedValue == ((long)CourseEnum.Learning).ToString() || ddlStatus.SelectedValue == ((long)CourseEnum.Exam_fail).ToString())
                    {
                        objRegisteredCoursesDB.Update(objRegisteredCourses);
                    }
                    else if (ddlStatus.SelectedValue == ((long)CourseEnum.Completed).ToString() || ddlStatus.SelectedValue == ((long)CourseEnum.Waiting_exam).ToString())
                    {
                        objRegisteredCoursesDB.Update(objRegisteredCourses);
                        List<CoursesScoes> lstScoes = objRegisteredCourses.lstCoursesScoes;



                        for (int i = 0; i < lstScoes.Count; i++)
                        {
                            lstScoes[i].IsCompleted = true;
                            objCourseScoesDB.Update(lstScoes[i]);

                        }

                        if (ddlStatus.SelectedValue == ((long)CourseEnum.Completed).ToString())
                        {
                            FinishedExamsDB objFinishedExamsDB = new FinishedExamsDB(ConnectionStrings.LMS);

                            FinishedExams objFininshed = new FinishedExams();
                            objFininshed.Degree = 100;
                            objFininshed.RegisteredCoursesID = objRegisteredCourses.ID;
                            objFininshed.Answers = "";
                            objFininshed.CurrentDate = DateTime.Now;
                            objFininshed.ExamIDs = "";
                            objFinishedExamsDB.Insert(objFininshed);
                            GlobalVars.addLog(objRegisteredCourses.ID, 4);
                            GlobalVars.sendLogMail(objRegisteredCourses, objRegisteredCourses.objPersons, 4);
                        }
                    }
                }

            }



        }

        if (lstFound.Count > 0)
        {
            if (lstFound[0].EmployeesID > 0)
            {
                bindSmallGrid(lstFound[0].EmployeesID);
            }
        }
        e.Cancel = true;

        

    }
   
    protected void grdCourses_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        e.Cancel = true;

        long lRegID = long.Parse(grdCourses.DataKeys[e.RowIndex]["ID"].ToString());

        RegisteredCoursesDB objRegisteredCoursesDB = new RegisteredCoursesDB(ConnectionStrings.LMS);

        List<RegisteredCourses> lstRemoved = objRegisteredCoursesDB.getRegisteredCoursesByID(lRegID);


        if (lstRemoved.Count > 0)
        {
            List<CoursesScoes> lstScoes = lstRemoved[0].lstCoursesScoes;
            foreach (CoursesScoes obj in lstScoes)
            {
                CoursesScoesDB objScoesDB = new CoursesScoesDB(ConnectionStrings.LMS);
                objScoesDB.Delete(obj);
            }


            List<UserLogs> lstLogs = lstRemoved[0].lstUserLogs;

            foreach (UserLogs obj in lstLogs)
            {
                UserLogsDB objUserLogsDB = new UserLogsDB(ConnectionStrings.LMS);
                objUserLogsDB.Delete(obj);
            }


            List<FinishedExams> lstFinishedExams = lstRemoved[0].lstFinishedExams;

            foreach (FinishedExams obj in lstFinishedExams)
            {
                FinishedExamsDB objFinishedExamsDB = new FinishedExamsDB(ConnectionStrings.LMS);
                objFinishedExamsDB.Delete(obj);
            }


            List<Exams> lstExams = lstRemoved[0].lstExams;

            foreach (Exams obj in lstExams)
            {
                ExamsDB objExamsDB = new ExamsDB(ConnectionStrings.LMS);
                objExamsDB.Delete(obj);
            }



            long lPersonID = lstRemoved[0].EmployeesID;

            objRegisteredCoursesDB.Delete(lstRemoved[0]);


            bindSmallGrid(lPersonID);
           

        }
    }



    /// <summary>
    /// this function will clear child grid
    /// </summary>
    private void clearChildGrid()
    {
        bindGrid(txtSearch.Text);

        mlstRegestered = new List<RegisteredCourses>();

        grdCourses.DataSource = mlstRegestered;
        grdCourses.DataBind();
    }

    /// <summary>
    /// this function will bind the courses grid
    /// </summary>
    /// <param name="PersonID">the person to bind courses grid with</param>
    private void bindSmallGrid(long PersonID)
    {
        List<Persons> lstFound = new List<Persons>(from obj in mlstPersons where obj.GenID == PersonID select obj);
        lstFound[0].clearchilds();
        if (lstFound.Count > 0)
        {
            mlstRegestered = lstFound[0].lstRegisteredCourses;
            grdCourses.DataSource = mlstRegestered;
            grdCourses.DataBind();
        }
        else
        {
            mlstRegestered = new List<RegisteredCourses>();

            grdCourses.DataSource = mlstRegestered;
            grdCourses.DataBind();
        }
    }
}